using System;
using System.Reflection;
using System.Collections.Generic;

namespace Open.Data.Persistence
{
    internal sealed class FieldComparer: IComparer<IPersistable>
    {
        private int _orderModifier;
        private PropertyInfo _info;

        public FieldComparer(ISort sort)
        {
            _orderModifier = (sort.Direction == SortDirection.Ascending) ? 1 : -1;
            _info = sort.PropertyInfo;
        }
       
        public int Compare(IPersistable x, IPersistable y)
        {
            IComparable comparerX = (IComparable) _info.GetValue(x, null);
            IComparable comparerY = (IComparable) _info.GetValue(y, null);

            if (x == y) return 0;
            if (comparerX == null) return -1;
            if (comparerY == null) return 1;                

            return comparerX.CompareTo(comparerY) * _orderModifier;
        }
    }
}